import React, { useState ,useEffect,useImperativeHandle,useRef} from 'react'
import './model.css'
import { Input, Steps, Select, message, Spin } from 'antd'
import { http} from '@/lib';
import apis from '@/apis/AboutQuota';
import MultiSelect from '../../GmApproval/multiSelect'
import { debounce } from '@/utils/methods';
const { Step } = Steps;
const {Option} = Select

const deleteimg = require('@/assets/delete.png')
let setFlowReqVos = []
const ModelContent = (props) =>{
  const [state, setstate] = useState(false)
  const [quotaNum, setQuotaNum] = useState('')
  const [template, setTemplate] = useState([])
  const [indexmg, setIndex] = useState(0)
  const [person, setPerson] = useState([])
  const [selectList, setSelectList] = useState([])
  const [inputValue, setInputValue] = useState([])
  const [fetching, setFetching] = useState(false)
  const [ CheckItem , setCheckItem] = useState<any>({})
  const [currentSelectPerson, setCurrentSelectPerson] = useState(-1)

  const childRef:any = useRef();
   useEffect(()=>{
     getTemplete()
     return ummonte()
   },[props.recordData])
   const ummonte = () =>{
    setSelectList([])
    setPerson([])
    setInputValue([])
    setCheckItem({})
    setFlowReqVos = []
   }
  const handleChange = value => {
    console.log(value);
    setInputValue(value)
    setFetching(false)
    let  recordData =  props.recordData
   const params = { //value.key
       brandCode:recordData.brandCode,
       dealerCode:value.key,
       productGroupId:recordData.productGroupId,
       quotaEndTime:recordData.quotaEndTime,
       quotaStartTime:recordData.quotaStartTime,
    }
    http.get(apis.QuotaModifyCheck,{params})
    .then(resp=>{ //校验比对
      setCheckItem(resp.data)
      setstate(true)
    })
  };
  const handelDelite = (index: number, id: any) =>{
      // setFlowReqVos = []
    let data = [...person]

    const curr = data[index].filter((a: any) => a.id !== id)

    data[index] = curr
    // data.splice(index, 1)
    sessionStorage.setItem('person', JSON.stringify(person))
    setPerson(data)
    setCurrentSelectPerson(index)
  }
 const fetchUser = value => {
    setFetching(true)
    debounce(()=>{
      requestSearchResult(value)
		},1000)()
  };
 const requestSearchResult =(value) =>{
  let  recordData =  props.recordData
  http.get(apis.QuotaModifyAgent,{params:{agentName:value,brandCode:recordData.brandCode}}).then(resp=>{
    setSelectList(resp.data)
  })
  .finally(()=>setFetching(false))
 }

  const getTemplete = () =>{ //获取审批模板
    let  recordData =  props.recordData
    http.get(apis.transferTemplate,{params:{brandCode:recordData.brandCode}})
    .then(resp=>{
       setTemplate(resp.data)
       let data = JSON.stringify(resp.data) 
       sessionStorage.setItem('role',data)
    })
  }
 const handelgetperson = (value) =>{
  if(currentSelectPerson == -1) return

  let data = [...person]
  data[currentSelectPerson] = value
  sessionStorage.setItem('person', JSON.stringify(person))
  setPerson(data)
 }

  const handleinput = (e) =>{ //inputd的值
    if(e.target.value<=props.recordData.quotaCanNum){
      setQuotaNum(e.target.value)
    }else{
      message.warning('转移配额数量不能大于配额数量')
    }
    
  }
  const  handelshowGM = (index) =>{ //审核model
    // childRef.current
       setIndex(index)
       childRef.current.handelCeck(index)
       setCurrentSelectPerson(index)
  }
  useImperativeHandle(props.onRef, () => ({
    // changeVal 就是暴露给父组件的方法
    changeVal: () => {
      let change:any = CheckItem
      //  let list = template.filter(item=>item.assignee.slice(0,1)=='$')
       if((person.length!=0&&template.length!=0)||(person.length==0&&template.length==0)){
        template.map((item, index)=>{
          const user = person[index] || []
          setFlowReqVos.push({name:item.assignee,userIds:user.map((a: any) => a.id) || []})
        })
      const params = {
        changId:change.id,
        id:props.recordData.id,
        quotaNum:quotaNum,
        workflowReqVos:setFlowReqVos
      }

      if(state==true){
        http.put(apis.QuotaModifyChange,params).then((resp)=>{
          message.success('提交成功!')
        })
      }else{
        message.error('配额有效期不一致，无法转移')
        return false
      }
    }else{
      message.warning('请选择审批人')
      return false
    }
  },
  handleCancel:()=>{
    setQuotaNum('')
  }  
}));
  return(
    <div className="weaperbox_model">
     <div style={{ width: 480 }}>
         <div className="weaper_model">
             <div>转出客户名称:</div>
             <Input type="text" disabled style={{ width: 350 }} value={props.recordData.dealerName} />
         </div>
         <div className="weaper_model">
             <div>物料分类名称:</div>
             <Input type="text" disabled style={{ width: 350 }} value={props.recordData.groupName}/>
         </div>
         <div className="text_model">
                <div>可用配额：  {props.recordData.quotaCanNum}件</div>
                <div>配额有效期：{props.time}</div>
            </div>
         <div className="weaper_model">
             <div>转移配额数量/件:</div>
             <Input type="text" 
             value={quotaNum} 
             placeholder="请输入转移配额数量"
             maxLength={20}
             style={{ width: 350 }}
             onChange={handleinput}
             />
         </div>
         <div className="weaper_model">
             <div>转入客户名称:</div>
                    <Select
                      showSearch
                      labelInValue
                      value={inputValue}
                      placeholder="请选择目标客户名称"
                      notFoundContent={fetching ? <Spin size="small" /> : null}
                      filterOption={false}
                      onSearch={fetchUser}
                      onChange={handleChange}
                      style={{ width: 350 }}
                    >
                      {selectList.map(d => (
                        <Option key={d.agentCode}>{d.agentName}</Option>
                      ))}
                   </Select>
         </div>
         <div className="weaper_model">
             <div>物料分类名称:</div>
             <Input type="text" disabled style={{ width: 350 }} value={props.recordData.groupName}/>
         </div>
         {/* ======== */}
          <div>
            <div>
               <div>转移后可用配额： {CheckItem.quotaCanNum==null?0+Number(quotaNum):CheckItem.quotaCanNum+Number(quotaNum)}件</div>
               <div>配额有效期：{(CheckItem.quotaStartTime || '--') + "至" + (CheckItem.quotaEndTime || '--')}</div>
            </div>
         </div>
         {/* ======== */}
         <div className="personcheck">请选择审批人：</div>
         <div className="Step_model">
            <Steps progressDot current={0} direction="vertical">
                {
                  template.map((item,index)=>(
                    <Step key={index} title={item.name} />
                  ))
                }
            </Steps>
            <div>
              {/* {
                template.map((item,index)=>(
                  <div className="waper-check" key={index}>
                    {((!person[index] || !person[index].length ))?
                      <div className="crli_model"  onClick={()=>handelshowGM(index)}>+</div>:
                      (person[index])?person[index].map(resp=>(
                        <div className="crli_tname" key={resp.id}>
                          <img src={deleteimg}  className="deleteimg" onClick={()=>handelDelite(index)} />
                          {resp.realName}
                        </div>
                       )):
                      item.userNames?.map((res,idx)=>(
                      <div className="crli_tname" key={idx}>{res}</div>   
                      ))
                     }
                  </div>
                ))
              } */}
              {
                template.map((item,index)=>(
                  <div className="waper-check" key={index}>
                    {
                      person[index] && person[index].map((resp: any) => (
                        <div className="crli_tname" key={resp.id}>
                          <img src={deleteimg}  className="deleteimg" onClick={()=>handelDelite(index, resp.id)} />
                          {resp.realName}
                        </div>
                      ))
                    }
                    <div className="crli_model"  onClick={()=>handelshowGM(index)}>+</div>
                  </div>
                ))
              }
          </div>
        </div>
      </div>
      <MultiSelect  cRef={childRef}  handelcilck={handelgetperson} />
     </div>

  )

}


export default ModelContent